<?php

/**
 * Example to dumping data into XML using Stream_Iterate as stream
 *
 * PHP version 5
 *
 * @category  Stream
 * @package   Stream_Iterate
 * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
 * @copyright 2008 11abacus / Philipe Jausions
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
 * @link      http://pear.11abacus.com/package/Stream_Iterate
 */

/**
 * Required packages
 */
require_once 'Stream/Iterate.php';

/**
 * Prints the XML header
 *
 * @param mixed $data Data of first iteration
 * 
 * @return string XML string
 */
function myXMLFormatStart($data)
{
    return '<?xml version="1.0"?><dataset>';
}

/**
 * Defines an XML "printer"
 *
 * @param array   $value     List of data to print out
 * @param integer $iteration Iteration counter (zero-based)
 *
 * @return string XML string
 */
function myXMLFormat(array $value, $iteration)
{
    if (empty($value)) {
        return '';
    }
    $xml = '<set counter="'.$iteration.'">';
    foreach ($value as $header => $data) {
        $xml .= '<'.$header.'>'
                .htmlspecialchars($data)
                .'</'.$header.'>';
    }
    return $xml."</set>\n";
}

/**
 * Prints the XML footer
 *
 * @param integer $iteration Last iteration count
 * 
 * @return string XML string
 */
function myXMLFormatEnd($iteration)
{
    return '</dataset>';
}

/**
 * Main
 */
stream_wrapper_register('foreach', 'Stream_Iterate');

$data = array(array('firstname' => 'John',
                    'lastname'  => 'Doe',
                    'city'      => 'Towneville'),
              array('lastname'  => 'Doe',
                    'city'      => 'Citybourg',
                    'firstname' => 'Jane'));

$context = stream_context_create(array(
    'foreach' => array(
        'data' => $data,
        'onFirst' => 'myXMLFormatStart', // Called just before data start to be read
        'toString' => 'myXMLFormat',     // Called to format data into string
        'onLast' => 'myXMLFormatEnd',    // Called just after the last data is read
    ),
));

echo file_get_contents('foreach://value@data', $flag, $context);

?>